/*
 * Copyright (c) 2024. hallele, Inc All rights reserved.
 */

package cn.hallele.ms.starter.web.filter;

import cn.hallele.infrastructure.metadata.constant.AppConst;
import cn.hallele.infrastructure.util.NetUtil;
import cn.hallele.infrastructure.util.ObjectUtil;
import cn.hallele.infrastructure.util.SecurityUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * hallele_mc_core
 *
 * @author anle5
 * @since 2024/9/22 17:17
 */
@Slf4j
@Component
@Order(10)
public class TraceIdFilter extends BaseFilter {
    /**
     * 自定义过滤器
     *
     * @param request     请求
     * @param response    响应
     * @param filterChain 过滤连
     */
    @Override
    protected void doCusInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestId = NetUtil.getRequestId();
        if (ObjectUtil.isBlank(requestId)) {
            requestId = SecurityUtil.randomString(18);
            log.warn("requestId is blank.System will create a requestId: {}.", requestId);
        }

        if (ObjectUtil.isBlank(MDC.get(AppConst.TRANCE_ID))) {
            MDC.put(AppConst.TRANCE_ID, requestId);
            log.warn("traceId is blank.System will create a traceId: {}.", MDC.get(AppConst.TRANCE_ID));
        }
        filterChain.doFilter(request, response);
    }
}
